<?php

namespace app\interfaces\controller;


use think\Db;
use think\View;
use think\Request;
use think\Exception;
use app\interfaces\model\Member as MemberModel;
use app\interfaces\model\Auction as AuctionModel;
use app\mobile\model\AuctionRecord as AuctionRecordModel;
use app\interfaces\model\AuctionGoods as AuctionGoodsModel;
use app\interfaces\model\MemberAuction as MemberAuctionModel;

class Auction
{

    // 拍卖推荐(web页)
    public function index()
    {
        // 实例化
        $auction_model = new AuctionModel();
        $auction_goods = new AuctionGoodsModel();
        $member_auction = new MemberAuctionModel();

        // 筛选
        $t = time();
        $start = mktime(0, 0, 0, date("m", $t), date("d", $t), date("Y", $t));
        $end = mktime(23, 59, 59, date("m", $t), date("d", $t), date("Y", $t));
        $con['start_time'] = ['between', [$start, $end]];

        // 获取数据
        $data = $auction_model->where($con)->field('id,end_time,status,picUrl,title,start_time')->order('create_time', 'desc')->paginate(3);

        $auction_str = '';
        foreach ($data as $value) {
            $auction_str .= $value['id'] . ',';
        }

        if (!empty($auction_str)) {

            $goods = $auction_goods->where('auction_id', 'in', $auction_str)->field('picUrl,title,auction_id,id,reserve_price')->limit(4)->select();

            foreach ($goods as &$value) {
                $value['person'] = $member_auction->where(['goods_id' => $value['id']])->count();
                $value['end_time'] = $auction_model->where('id', $value['auction_id'])->value('end_time');
            }
        } else {
            $goods = [];
        }


        $view = new View();

        echo $view->fetch('', [
            'data'  => $data,
            'goods' => $goods
        ]);


    }


    // 历史拍卖
    public function history()
    {

        // 筛选 今天之前的拍卖
        $t = time();
        $start = mktime(0, 0, 0, date("m", $t), date("d", $t), date("Y", $t));
        $condition['end_time'] = ['lt', $start];

        // 获取数据
        $model = new AuctionModel();
        $data = $model->where($condition)->field('id,end_time,status,picUrl,title,start_time')->order('create_time', 'desc')->paginate(10, false);


        $view = new View();

        echo $view->fetch('', [
            'data' => $data
        ]);

    }


    // 拍卖主页
    public function auction()
    {
        // 实例化
        $auction = new AuctionModel();
        $auction_goods = new AuctionGoodsModel();
        $member_auction = new MemberAuctionModel();

        // 获取拍卖活动ID
        $auction_id = Request::instance()->param('id');

        // 此类活动结束时间
        $end_time = $auction->where('id', $auction_id)->value('end_time');

        $data = $auction_goods->where('auction_id', $auction_id)->field('id,title,picUrl,deal_price')->select();

        foreach ($data as &$value) {
            $value['person'] = $member_auction->where('goods_id', $value['id'])->count('id');
        }

        // banner图
        $banner_list = (new AuctionGoodsModel())->where('auction_id', $auction_id)->limit(3)->select();


        $view = new View();
        echo $view->fetch('', [
            'end_time'    => $end_time,
            'data'        => $data,
            'banner_list' => $banner_list
        ]);

    }


    // 拍卖商品详情
    public function detail()
    {
        // 获取参数
        $goods_id = Request::instance()->param('goods_id');

        // 实例化
        $model = new AuctionGoodsModel();

        // 获取数据
        $item = $model->where('id', $goods_id)->find();

        // 拍卖活动信息
        $start_time = (new AuctionModel())->where('id', $item['auction_id'])->value('start_time');


        $view = new View();

        echo $view->fetch('', [
            'item'       => $item,
            'start_time' => $start_time,
        ]);


    }


    // 拍卖房间
    public function spot()
    {

        // 获取参数
        $goods_id = Request::instance()->param('id');
        $member_id = Request::instance()->param('user_id');


        // 获取商品信息
        $data = (new AuctionGoodsModel())->where('id', $goods_id)->find();


        $find = (new MemberAuctionModel())->where(['member_id' => $member_id, 'goods_id' => $goods_id, 'auction_id' => $data['auction_id']])->find();

        if ($find) {
            $bond = 1;
        } else {
            $bond = 2;
        }

        // 获取拍卖信息
        $action = (new AuctionModel())->where('id', $data['auction_id'])->find();

        // 拍卖纪录表实例化
        $model = new AuctionRecordModel();

        $record = $model->with('Member')->where('goods_id', $goods_id)->order('id', 'desc')->select();

        // 如果记录不为空
        $first = "";
        if (count($record)>0) {
            $first = $record[0];
        }
        $dijia = 0;
        if (count($record)>0) {
            $dijia = Db::name('auction_record')->where('goods_id', $goods_id)->max('bind');
        } else {
            $dijia = $data['starting_price'];
        }

        if ($action['end_time'] < time()) {
            self::shengcheng($goods_id);


        }

        $view = new View();

        echo $view->fetch('', [
            'record'   => $record,
            'data'     => $data,
            'action'   => $action,
            'dijia'    => $dijia,
            'goods_id' => $goods_id,
            'bond'     => $bond,
            'first'    => $first
        ]);

    }


    // 拍卖详情Web页
    public function selling()
    {
        $goods_id = Request::instance()->param('goods_id');
        $draw_id = Request::instance()->param('draw_id');

        $end_time = (new AuctionModel())->where('id', $draw_id)->value('end_time');

        $model = new AuctionRecordModel();

        // 如果拍卖活动未结束
        if ($end_time > time()) {
            // $record = $model->with('member')->where('goods_id', $goods_id)->order('id', 'desc')->select();
            $record = $model->where('goods_id', $goods_id)->order('id', 'desc')->select()->toArray();
            foreach ($record as &$value) {
                $msn = (new MemberModel())->where('id', $value['member_id'])->field('id,nickname,avatar')->find();
                $value['member']['id'] = $msn['id'];
                $value['member']['nickname'] = $msn['nickname'];
                $value['member']['avatar'] = $msn['avatar'];
            }
            $current_price = $model->where('goods_id', $goods_id)->max('bind');
            $person_member_id = $model->where(['goods_id' => $goods_id, 'bind' => $current_price])->value('member_id');
            $person = (new MemberModel())->where('id', $person_member_id)->value('nickname');
            $avatar = (new MemberModel())->where('id', $person_member_id)->value('avatar');
            if ($record) {
                return ['code' => 200, 'brands' => $record, 'currents' => $current_price, 'person' => $person, 'avatar' => $avatar];
            }
        } else {
            // 如果拍卖活动已结束 获取出价最高的一条信息
            $bind = $model->where('goods_id', $goods_id)->max('bind');
            $user = $model->where(['goods_id' => $goods_id, 'bind' => $bind])->find();
            $person = (new MemberModel())->where('id', $user['member_id'])->value('nickname');

            $find = Db::name('auction_order')->where('goods_id', $goods_id)->find();
            if ($find) {

                return ['code' => 203, 'bind' => $bind, 'person' => $person];
            }

            // 获取低价
            $reserve_price = (new AuctionGoodsModel())->where('id', $goods_id)->value('reserve_price');

            if ($bind > $reserve_price) {
                Db::startTrans();
                $current_price = $model->where('goods_id', $goods_id)->max('bind');
                $person_member_id = $model->where(['goods_id' => $goods_id, 'bind' => $current_price])->value('member_id');
                try {
                    $goods = (new AuctionGoodsModel())->where('id', $goods_id)->find();
                    // 拍卖订单生成
                    $ini = [
                        'member_id'      => $person_member_id,
                        'goods_id'       => $goods_id,
                        'title'          => $goods['title'],
                        'picUrl'         => $goods['picUrl'],
                        'order_number'   => self::createNumber(),
                        'price'          => $bind,
                        'address_name'   => '',
                        'address_phone'  => '',
                        'address_area'   => '',
                        'address_site'   => '',
                        'status'         => 0,
                        'way'            => '未支付',
                        'express_number' => '',
                        'express_name'   => '',
                        'express_value'  => '',
                    ];

                    // 生成拍卖订单
                    Db::name('auction_order')->insert($ini);

                    // 拍卖商品信息
                    $condition = [
                        'deal_price' => $bind,
                        'deal_time'  => time(),
                        'member_id'  => $person_member_id,
                    ];

                    (new AuctionGoodsModel())->save($condition, ['id' => $goods_id]);

                    Db::commit();

                    return ['code' => 201, 'brands' => $bind, 'person' => $person];

                } catch (\Exception $e) {

                    // 回滚事务
                    Db::rollback();

                    return ['code' => 404, 'message' => '数据错误'];

                }


            } else {
                return ['code' => 402, 'message' => '此商品留拍'];
            }


        }
    }


    // 生成拍卖订单
    public function shengcheng($goods_id)
    {


        $model = new AuctionRecordModel();

        $bind = $model->where('goods_id', $goods_id)->max('bind');

        // 获取低价
        $reserve_price = (new AuctionGoodsModel())->where('id', $goods_id)->value('reserve_price');

        if ($bind > $reserve_price) {

            $find = Db::name('auction_order')->where('goods_id', $goods_id)->find();

            if (!empty($find)) {
                return false;
            }


            Db::startTrans();

            $current_price = $model->where('goods_id', $goods_id)->max('bind');
            $person_member_id = $model->where(['goods_id' => $goods_id, 'bind' => $current_price])->value('member_id');
            try {
                $goods = (new AuctionGoodsModel())->where('id', $goods_id)->find();
                // 拍卖订单生成
                $ini = [
                    'member_id'      => $person_member_id,
                    'goods_id'       => $goods_id,
                    'title'          => $goods['title'],
                    'picUrl'         => $goods['picUrl'],
                    'order_number'   => self::createNumber(),
                    'price'          => $bind,
                    'address_name'   => '',
                    'address_phone'  => '',
                    'address_area'   => '',
                    'address_site'   => '',
                    'status'         => 0,
                    'way'            => '未支付',
                    'express_number' => '',
                    'express_name'   => '',
                    'express_value'  => '',
                ];

                // 生成拍卖订单
                Db::name('auction_order')->insert($ini);

                // 拍卖商品信息
                $condition = [
                    'deal_price' => $bind,
                    'deal_time'  => time(),
                    'member_id'  => $person_member_id,
                ];

                (new AuctionGoodsModel())->save($condition, ['id' => $goods_id]);

                Db::commit();

                return true;

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return false;

            }
        }
    }


    public function chujia()
    {
        if (Request::instance()->isPost()) {

            $member_id = Request::instance()->param('user_id');

            $goods_id = Request::instance()->param('goods_id');

            $draw_id = Request::instance()->param('draw_id');
            $auction = new AuctionModel();
            $model = new AuctionRecordModel();
            $start_time = $auction->where('id', $draw_id)->value('start_time');
            if ($start_time > time()) {
                return ['code' => 405, 'message' => 2];
            }

            if (!empty($goods_id) && !empty($member_id)) {

                $goods = new AuctionGoodsModel();
                $data = $goods->where('id', $goods_id)->find();
                $mon = $model->where('goods_id', $goods_id)->max('bind');
                $now_mon = $model->where(['member_id' => $member_id, 'goods_id' => $goods_id])->max('bind');

                if (!empty($now_mon)) {
                    if ($mon == $now_mon) {
                        return ['code' => 202];
                    }
                }


                $now_price = '';
                if ($data['deal_price'] == 0) {
                    $now_price = $data['starting_price'] + $data['bidding'];
                } else {
                    $now_price = $data['deal_price'] + $data['bidding'];
                }


                Db::startTrans();

                try {

                    $goods->save(['deal_price' => $now_price], ['id' => $goods_id]);

                    $con = [
                        'auction_id'  => $draw_id,
                        'goods_id'    => $goods_id,
                        'member_id'   => $member_id,
                        'bind'        => $now_price,
                        'update_time' => time()
                    ];

                    $model->allowField(true)->save($con);

                    // 判断时间 延长拍卖时间
                    $auction = new AuctionModel();
                    $end_time = $auction->where('id', $draw_id)->value('end_time');
                    $now_time = time() + 300;
                    if ($end_time < $now_time) {
                        // 延长五分钟
                        $new_end_time = $end_time + 300;
                        $auction->save(['end_time' => $new_end_time], ['id' => $draw_id]);
                    }

                    Db::commit();

                    return ['code' => 200, 'price' => $now_price];

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ['code' => 402, 'message' => 2];

                }


            } else {
                return ['code' => 402, 'message' => 1];
            }
        }


    }


    public function bond()
    {
        $member_id = Request::instance()->param('user_id');
        $goods_id = Request::instance()->param('goods_id');
        $pass = (new MemberModel())->where('id', $member_id)->value('pay_pass');
        $bond = (new AuctionGoodsModel())->where('id', $goods_id)->value('bond');
        $blance_price = Db::name('member')->where('id', $member_id)->value('balance');

        if ($pass) {
            $check_pass = 1;
        } else {
            $check_pass = 2;
        }

        return ['code' => 200, 'pass' => $check_pass, 'bond' => $bond, 'blance_price' => $blance_price];

    }


    public function balance()
    {
        if (Request::instance()->isPost()) {
            // 会员ID
            $member_id = Request::instance()->param('user_id');
            // 拍卖商品ID
            $goods_id = Request::instance()->param('goods_id');
            // 支付密码
            $pass = (new MemberModel())->where('id', $member_id)->value('pay_pass');

            $find = (new AuctionGoodsModel())->where('id', $goods_id)->find();
            $price = $find['bond'];
            $blance_price = Db::name('member')->where('id', $member_id)->value('balance');

            if ($blance_price < $price) return ['code' => 404, 'message' => '余额不足'];

            Db::startTrans();
            try {

                // 会员拍卖纪录增加
                $ini = [
                    'auction_id'    => $find['auction_id'],
                    'goods_id'      => $goods_id,
                    'member_id'     => $member_id,
                    'reserve_price' => $price,
                    'status'        => 2
                ];

                (new MemberAuctionModel())->allowField(true)->save($ini);

                // 减少余额

                Db::name('member')->where('id', $member_id)->setDec('balance', $price);

                $con = [
                    'member_id'    => $member_id,
                    'type_id'      => 4,
                    'price'        => $price,
                    'way'          => '保证金充值',
                    'balance'      => $blance_price,
                    'status'       => 1,
                    'reason'       => '',
                    'order_number' => '',
                    'create_time'  => time(),
                ];

                Db::name('member_withdraw')->insert($con);

                Db::commit();

                return ['code' => 200, 'message' => '支付成功'];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 404, 'message' => '支付失败'];
            }
        }
    }


    // 拍卖订单
    public function order_list()
    {
        // 获取类型 未付款 已付款
        $type = Request::instance()->param('status', 0);
        $member_id = Request::instance()->param('user_id');

        // 筛选
        $condition['member_id'] = $member_id;
        $condition['status'] = $type;
        $data = Db::name('auction_order')->where($condition)->order('id', 'desc')->select();


        return ['code' => 200, 'message' => 'OK', 'data' => $data];
    }


    // 拍卖中的订单
    public function order_selling()
    {
        $user_id = Request::instance()->param('user_id');
        // 查询仍然在竞拍的活动
        $model = new AuctionModel();
        $t = time();
        $start = mktime(0, 0, 0, date("m", $t), date("d", $t), date("Y", $t));
        $end = mktime(23, 59, 59, date("m", $t), date("d", $t), date("Y", $t));
        $con['start_time'] = ['between', [$start, $end]];
        $con['end_time'] = ['gt', time()];
        $data = $model->where($con)->field('id')->order('create_time', 'desc')->select();

        // 查找符合条件的商品
        $auction_str = '';
        foreach ($data as $value) {
            $auction_str .= $value['id'] . ',';
        }

        $ini = [
            'member_id'  => $user_id,
            'auction_id' => ['in', $auction_str],
        ];

        $pai_mai = (new MemberAuctionModel)->where($ini)->field('id,member_id,auction_id,goods_id')->select();

        $arr = [];
        foreach ($pai_mai as $k => $value) {
            if (!in_array($value->auction_id, $arr)) {
                $arr[] = $value->auction_id;
            } else {
                unset($pai_mai[$k]);
            }
        }

        foreach ($pai_mai as &$value) {
            $value['goods'] = (new AuctionGoodsModel())->where('id', $value['goods_id'])->field('id,picUrl,title')->find();
            $ling = (new AuctionRecordModel())->where(['goods_id' => $value['goods_id'], 'member_id' => $user_id])->order('id', 'desc')->limit(1)->value('bind');
            $max_price = (new AuctionRecordModel())->where('goods_id', $value['goods_id'])->max('bind');
            $value['max_price'] = $max_price;
            $value['end_time'] = date('H:i:s', (new AuctionModel())->where('id', $value['auction_id'])->value('end_time'));
            $value['url'] = Request::instance()->domain() . "/index.php/interfaces/auction/spot?id=" . $value['goods_id'];
            $count = (new MemberAuctionModel())->where(['goods_id' => $value['goods_id']])->count();
            $value['my_price'] = $ling;
            if ($ling == $max_price) {
                $value['ling'] = 1;
            } else {
                $value['ling'] = 2;
            }
            $value['count'] = $count;

        }


        return ['code' => 200, 'message' => 'OK', 'data' => $pai_mai];
    }


    // 拍卖订单详情
    public function order()
    {
        $id = Request::instance()->param('id');
        $user_id = Request::instance()->param('user_id');


        $item = Db::name('auction_order')->where('id', $id)->find();

        $item['goods'] = Db::name('auction_goods')->where('id', $item['goods_id'])->find();

        //用户默认收货地址
        $address = (new MemberAddress)->where(['member_id' => $user_id, 'status' => 1])->field('name,phone,address,area_info')->find();


        return ['code' => 200, 'message' => 'OK', 'item' => $item, 'address' => $address];


    }

    // 确认收货
    public function confirmation()
    {
        // 获取参数
        $order_id = Request::instance()->param('order_id');

        $operation = Db::name('auction_order')->where('id', $order_id)->update(['status' => 3]);

        if ($operation) {
            return ['code' => 200, 'message' => 'OK'];
        }else{
            return ['code' => 404, 'message' => '系统繁忙，请稍后再试'];
        }

    }

    // 生成订单
    public function generating_order()
    {
        $order_id = Request::instance()->param('order_id');
        $address_name = Request::instance()->param('address_name');
        $address_phone = Request::instance()->param('address_phone');
        $address_area = Request::instance()->param('address_area');
        $address_site = Request::instance()->param('address_site');

        if (empty($order_id)||empty($address_name)||empty($address_phone)||empty($address_area)||empty($address_site)) throw new Exception('not Empty');

        $operation = Db::name('auction_order')->where('id', $order_id)->update([
            'address_name'  => $address_name,
            'address_phone' => $address_phone,
            'address_area'  => $address_area,
            'address_site'  => $address_site
        ]);

        if ($operation||$operation==0) {
            return ['code' => 200, 'message' => 'OK'];
        } else {
            return ['code' => 404, 'message' => '系统繁忙，请稍后再试'];
        }
    }


    // 余额支付拍卖订单
    public function payment()
    {
        if (Request::instance()->isPost()) {
            $order_number = Request::instance()->param('order_number');
            $user_id = Request::instance()->param('user_id');
            Db::startTrans();
            try {
                $price = Db::name('auction_order')->where(['member_id' => $user_id, 'status' => '0', 'order_number' => $order_number])->value('price');

                Db::name('auction_order')->where(['member_id' => $user_id, 'status' => '0', 'order_number' => $order_number])->update(['status' => 1]);

                Db::name('member')->where('id', $user_id)->setDec('balance', $price);

                $balance = Db::name('member')->where('id', $user_id)->value('balance');

                $con = [
                    'member_id'    => $user_id,
                    'type_id'      => 4,
                    'price'        => $price,
                    'way'          => '拍卖订单支付',
                    'balance'      => $balance,
                    'status'       => 2,
                    'reason'       => '',
                    'order_number' => $order_number,
                    'create_time'  => time(),
                ];

                Db::name('member_withdraw')->insert($con);

                Db::commit();

                return ['code' => 200, 'message' => '支付成功'];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 404, 'message' => '支付失败'];
            }

        }
    }


    // 生成订单号
    protected function createNumber()
    {

        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }

        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }

    /*
 * id
 * address_name
 * address_phone
 * address_area
 */
    public  function  auction_order_dizhi()
    {
        $data = Request::instance()->param();
        if (empty($data['id'])) return ['code' => '403', 'message' => '请选择一个订单'];
        Db::name('auction_order')->where('id', $data['id'])->update(['address_name' => $data['address_name'],
            'address_phone' => $data['address_phone'],
            'address_area' => $data['address_area'], 'address_site' => $data['address_site']]);
        {
            return ['code' => 200, 'message' => '成功'];


        }
    }


}